//
//  WShareUtil.m
//  WArtMarket
//
//  Created by 武根宝 on 17/1/24.
//  Copyright © 2017年 环球巨人. All rights reserved.
//

#import "WShareUtil.h"
#import "sys/utsname.h"
#import "KeyChainStore.h"
#import "WaitingView.h"
#import "UIView+WaitingView.h"
#import "AFNetworking.h"

static NSString *availableUrl = PCReleaseURL;

@implementation WShareUtil

-(id)init{
    if (self = [super init]) {
        _arrMdiagram = [NSMutableArray array];
        _Who = @"";
        _cirReqNum = 0;
        _reqNum = 0;
    }
    return self;
}

+ (void)showWait:(BOOL)isShow frame:(CGRect)frame{

    if (isShow) {
        WaitingView *waitingView = [[WaitingView alloc] initWithFrame:frame tag:58000];
        [waitingView.contentView startAnimating];
//        waitingView.backgroundColor = WRGBAColor(0, 0, 0, 0.5);
        [[[UIApplication sharedApplication] delegate].window addSubview:waitingView];
    }
    else{
        WaitingView *waitingView = [[[UIApplication sharedApplication] delegate].window viewWithTag:58000];
        [waitingView.contentView stopAnimating];
        [waitingView removeFromSuperview];
    }
}

+ (WShareUtil *)sharedData{
    static WShareUtil *shareData = nil;
    static dispatch_once_t oneToken;
    dispatch_once(&oneToken, ^{
        shareData = [[self alloc] init];
    });
    return shareData;
}

//获取服务地址 拼接请求链接
+(NSString *)getServerURL:(NSString *)url{

    NSString *strURL =@"";

    //是否为发布版本   标志 BOOL
    if (PCReleaseFlag) {
        //拼接发布版本
        strURL = availableUrl;
    }else {
        //拼接测试版本
        strURL = PCDebugURL;
//        strURL = [WShareUtil getDataWithUserDefaultsForKey:@"DEBUGURL"];
//        if ([WShareUtil strNilOrEmpty:strURL]) {
//            strURL = PCDebugURL;
//        }
    }
    if (url != nil) {
        strURL =[NSString stringWithFormat:@"%@/%@",strURL,url];
    }
    return strURL;
}

//是否越狱
+(BOOL)isJailBreak{
    NSString *USER_APP_PATH =@"/User/Applications/";
    if ([[NSFileManager defaultManager] fileExistsAtPath:USER_APP_PATH]) {
        //这个是利用不越狱的机器没有这个权限来判定的
        return YES;
    }
    return NO;
}

+ (NSString *)stringByTrimmingCharactersInSetOrSpaceStr:(NSString *)str{
    NSString* headerData= str;
    headerData = [headerData stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];  //去除掉首尾的空白字符和换行字符
    headerData = [headerData stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    headerData = [headerData stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return headerData;

}

//判断字符串空或nil
+ (BOOL)strNilOrEmpty:(NSString *)string{
    if ([string isKindOfClass:[NSString class]])
    {
        if (string.length > 0)
        {
            return NO;
        }
        else
        {
            return YES;
        }
    }
    else
    {
        return YES;
    }
}


//获取当前时间的时间托
+(NSString *)timeString{
    NSDate *now = [NSDate date];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = kCFCalendarUnitYear | kCFCalendarUnitMonth | kCFCalendarUnitDay | kCFCalendarUnitHour | kCFCalendarUnitMinute | kCFCalendarUnitSecond;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    
    NSInteger year = [dateComponent year];
    NSInteger month = [dateComponent month];
    NSInteger day = [dateComponent day];
    NSInteger hour = [dateComponent hour];
    NSInteger minute = [dateComponent minute];
    NSInteger second = [dateComponent second];
    
    NSString *sTime = [NSString stringWithFormat:@"%ld%02ld%02ld%02ld%02ld%02ld",(long)year,(long)month,(long)day,(long)hour,(long)minute,(long)second];
    return sTime;
}

+(NSString * )GetDeviceRealType
{
    // 需要#import "sys/utsname.h"
    
    struct utsname systemInfo;
    
    uname(&systemInfo);
    
    NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    //iphone
    if ([platform isEqualToString:@"iPhone1,1"])   return @"iPhone 2G";
    if ([platform isEqualToString:@"iPhone1,2"])   return @"iPhone 3G";
    if ([platform isEqualToString:@"iPhone2,1"])   return @"iPhone 3GS";
    if ([platform isEqualToString:@"iPhone3,1"])   return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone3,2"])   return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone3,3"])   return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone4,1"])   return @"iPhone 4S";
    if ([platform isEqualToString:@"iPhone5,1"])   return @"iPhone 5";
    if ([platform isEqualToString:@"iPhone5,2"])   return @"iPhone 5";
    if ([platform isEqualToString:@"iPhone5,3"])   return @"iPhone 5c";
    if ([platform isEqualToString:@"iPhone5,4"])   return @"iPhone 5c";
    if ([platform hasPrefix:@"iPhone6,"])   return @"iPhone 5s";
    if ([platform isEqualToString:@"iPhone7,2"])   return @"iPhone 6";
    if ([platform isEqualToString:@"iPhone7,1"])   return @"iPhone6 Plus";
    if ([platform isEqualToString:@"iPhone8,1"])   return @"iPhone 6s";
    if ([platform isEqualToString:@"iPhone8,2"])   return @"iPhone6s Plus";
    
    //ipod
    if ([platform isEqualToString:@"iPod1,1"])     return @"iPod Touch 1";
    if ([platform isEqualToString:@"iPod2,1"])     return @"iPod Touch 2";
    if ([platform isEqualToString:@"iPod3,1"])     return @"iPod Touch 3";
    if ([platform isEqualToString:@"iPod4,1"])     return @"iPod Touch 4";
    if ([platform isEqualToString:@"iPod5,1"])     return @"iPod Touch 5";
    if ([platform isEqualToString:@"iPod5,1"])     return @"iPod Touch 5";
    if ([platform isEqualToString:@"iPod7,1"])     return @"iPod Touch 6";
    //ipad
    if ([platform isEqualToString:@"iPad1,1"])     return @"iPad";
    if ([platform isEqualToString:@"iPad1,2"])     return @"iPad 3G";
    if ([platform isEqualToString:@"iPad2,1"])     return @"iPad 2";
    if ([platform isEqualToString:@"iPad2,2"])     return @"iPad 2";
    if ([platform isEqualToString:@"iPad2,3"])     return @"iPad 2";
    if ([platform isEqualToString:@"iPad2,4"])     return @"iPad 2";
    if ([platform isEqualToString:@"iPad3,1"])     return @"iPad 3";
    if ([platform isEqualToString:@"iPad3,2"])     return @"iPad 3";
    if ([platform isEqualToString:@"iPad3,3"])     return @"iPad 3";
    if ([platform isEqualToString:@"iPad3,4"])     return @"iPad 4";
    if ([platform isEqualToString:@"iPad3,5"])     return @"iPad 4";
    if ([platform isEqualToString:@"iPad3,6"])     return @"iPad 4";
    if ([platform isEqualToString:@"iPad2,5"])     return @"iPad Mini";
    if ([platform isEqualToString:@"iPad2,6"])     return @"iPad Mini";
    if ([platform isEqualToString:@"iPad2,7"])     return @"iPad Mini";
    if ([platform isEqualToString:@"iPad4,4"])     return @"iPad Mini2";
    if ([platform isEqualToString:@"iPad4,5"])     return @"iPad Mini2";
    if ([platform isEqualToString:@"iPad4,6"])     return @"iPad Mini2";
    if ([platform isEqualToString:@"iPad4,7"])     return @"iPad Mini3";
    if ([platform isEqualToString:@"iPad4,8"])     return @"iPad Mini3";
    if ([platform isEqualToString:@"iPad4,9"])     return @"iPad Mini3";
    if ([platform isEqualToString:@"iPad5,1"])     return @"iPad Mini4";
    if ([platform isEqualToString:@"iPad5,2"])     return @"iPad Mini4";
    if ([platform isEqualToString:@"iPad4,1"])     return @"iPad Air";
    if ([platform isEqualToString:@"iPad4,2"])     return @"iPad Air";
    if ([platform isEqualToString:@"iPad4,3"])     return @"iPad Air";
    if ([platform isEqualToString:@"iPad5,3"])     return @"iPad Air2";
    if ([platform isEqualToString:@"iPad5,4"])     return @"iPad Air2";
    
    
    //if ([platform hasPrefix:@"iPad4,"])     return @"iPad";
    //模拟器
    if ([platform isEqualToString:@"i386"])        return @"Simulator";
    if ([platform isEqualToString:@"x86_64"])      return @"Simulator";
    
    return platform;
}

+(NSString *)getDeviceInfo
{
    NSString * strofDeviceInfo = [NSString stringWithFormat:@"%@|%@|%@",[WShareUtil getDeviceNumber],[[UIDevice currentDevice] model],[WShareUtil getDeviceOSType]];
    return strofDeviceInfo;
}

+(NSString *)getDeviceOSType
{
    NSString *systemVersion =  [NSString stringWithFormat:@"%@",[[UIDevice currentDevice] systemVersion]];
    
    return systemVersion;
}

+(NSString *)getDeviceNumber
{
    UIDevice *device = [UIDevice currentDevice];
    
    return [[device identifierForVendor] UUIDString];
}

// 得到一个随即的字符串，输入长度
+ (NSString *)getStringWithLength:(NSUInteger)length
{
    NSMutableString *string = [[NSMutableString alloc] init];
    for (int i = 0; i < length; i++) {
        NSString *character = [WShareUtil getAnCharacter];
        [string appendString:character];
    }
    return string;
}

// 得到一个随即字符,从以下字符中取一个
+ (NSString *)getAnCharacter
{
    NSArray *array = [[NSArray alloc] initWithObjects:@"0", @"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", nil];
    NSUInteger index = rand() % array.count;
    NSString *character = [array objectAtIndex:index];
    return character;
}

+ (void)openUrl:(NSString *)url{
    NSURL *verURL = [NSURL URLWithString:url];
    [[UIApplication sharedApplication] openURL:verURL];
}

// 角度转弧度
+ (CGFloat)degreeToRadian:(CGFloat)degrees{
    return degrees * M_PI / 180;
}

// 弧度转角度
+ (CGFloat)radianToDegree:(CGFloat)radians{
    return radians * 180 / M_PI;
}

//将十六进制的颜色值转换为uicolor:rrggbbhh
+ (UIColor*)hexColor:(NSString*)hexColor
{
    unsigned int red, green, blue, alpha;
    alpha = 100;
    NSRange range;
    range.length = 2;
    @try {
        if ([hexColor hasPrefix:@"#"]) {
            hexColor = [hexColor stringByReplacingOccurrencesOfString:@"#" withString:@""];
        }
        range.location = 0;
        [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&red];
        range.location = 2;
        [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&green];
        range.location = 4;
        [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&blue];
        
        if ([hexColor length] > 6) {
            range.location = 6;
            [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&alpha];
        }
    }
    @catch (NSException * e) {
        WLog(@"颜色值错误!");
        return [UIColor blackColor];
    }
    
    return [UIColor colorWithRed:(float)(red/255.0f) green:(float)(green/255.0f) blue:(float)(blue/255.0f) alpha:(float)(alpha/100.0f)];
}

+(BOOL)writeImage:(UIImage*)image toFileAtPath:(NSString*)aPath {
    if ((image == nil) || (aPath == nil) || ([aPath isEqualToString:@""]))
        return NO;
    @try {
        NSData *imageData = nil;
        NSString *ext = [aPath pathExtension];
        if ([ext isEqualToString:@"png"]) {
            imageData = UIImagePNGRepresentation(image);
        } else {
            // the rest, we write to jpeg
            // 0. best, 1. lost. about compress.
            imageData = UIImageJPEGRepresentation(image, 0);
        }
        if ((imageData == nil) || ([imageData length] <= 0))
            return NO;
        [imageData writeToFile:aPath atomically:YES];
        return YES;
    } @catch (NSException *e) {
        WLog(@"create thumbnail exception.");
    }
    return NO;
}

#pragma mark -
#pragma mark File

+(NSString *)fileMainBundleName:(NSString *)strFileName{
    
    NSString *strBundle =[[NSBundle mainBundle] bundlePath];
    return [strBundle stringByAppendingPathComponent:strFileName];
}


+(NSString *)fileLibCacheDirectory{
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    return basePath;
}

//获取Documents目录地址
+(NSString *)fileDocumentsDirectory{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    return basePath;
}

//获取temp临时文件夹地址
//filename 文件名称
+(NSString*)fileTempDirectoryWithFile:(NSString *)filename{
    return [NSTemporaryDirectory() stringByAppendingPathComponent:filename];
}


//创建目录
+(BOOL)fileCreateDirectory:(NSString *)directoryPath{
    NSFileManager *filemanager = [NSFileManager defaultManager];
    
    return [filemanager createDirectoryAtPath:directoryPath withIntermediateDirectories:NO attributes:nil error:nil];

}

//是否存在目录或文件
+(BOOL)fileIsExistPath:(NSString *)filePath{
    NSFileManager *filemanager = [NSFileManager defaultManager];
    return [filemanager fileExistsAtPath:filePath];
}

//创建文件
+(BOOL)fileWriteToPath:(NSString *)filePath data:(NSData*)data{
    return [data writeToFile:filePath atomically:YES];
}

//删除文件
+(BOOL)fileDelete:(NSString *)filePath{
    NSFileManager *filemanager = [NSFileManager defaultManager];
    NSError *error;
    if ([filemanager removeItemAtPath:filePath error:&error] != YES){
        //		[BTProjectUtil showLog:@"%@ deleteFile %@",[self description],[error localizedDescription]];
        return NO;
    }
    return YES;
}

//获取目录下所有文件名称
+(NSArray *)fileSubFileNames:(NSString *)filePath{
    NSFileManager *filemanager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *names = [filemanager contentsOfDirectoryAtPath:filePath error:&error];
    return names;
}

+(BOOL)fileCopy:(NSString *)sourcePath toPath:(NSString*)toPath{
    NSFileManager *filemanager = [NSFileManager defaultManager];
    return [filemanager copyItemAtPath:sourcePath toPath:toPath error:NULL];
}

//计算文件夹下文件的总大小
+(long)fileSizeForDir:(NSString*)path {
    int size = 0;
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    NSArray* array = [fileManager contentsOfDirectoryAtPath:path error:nil];
    for(int i = 0; i<[array count]; i++) {
        NSString *fullPath = [path stringByAppendingPathComponent:[array objectAtIndex:i]];
        BOOL isDir;
        if ( !([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && isDir) ) {
            NSDictionary *fileAttributeDic=[fileManager attributesOfItemAtPath:fullPath error:nil];
            size += fileAttributeDic.fileSize;
        } else {
            [self fileSizeForDir:fullPath];
        }
    }
    return size;
}

+ (UIImage *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength {
    // Compress by quality
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    if (data.length < maxLength) return image;
    
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    UIImage *resultImage = [UIImage imageWithData:data];
    if (data.length < maxLength) return resultImage;
    
    // Compress by size
    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        CGFloat ratio = (CGFloat)maxLength / data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)), (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        data = UIImageJPEGRepresentation(resultImage, compression);
    }
    
    return resultImage;
}

#pragma mark--自适应高度宽度
+ (CGSize)calculationHeightWidth:(NSString *)str andSize:(float)fontSize andCGSize:(CGSize)size{
    
    if([str isEqual:@""]){
        return CGSizeMake(0, 0);
    }
    
    UIFont * tfont = [UIFont systemFontOfSize:fontSize];
    
    NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:tfont,NSFontAttributeName,nil];
    
    return [str boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin  attributes:tdic context:nil].size;
    
}

+ (BOOL)systemVersionCompare{
    NSString *versionStr = [[UIDevice currentDevice].systemVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
    if (versionStr.length <= 1) {
        versionStr = [versionStr stringByAppendingString:@"00"];
    } else if (versionStr.length <= 2) {
        versionStr = [versionStr stringByAppendingString:@"0"];
    }
    CGFloat version = versionStr.floatValue;
    // 目前已知8.0.0 - 8.0.2系统，拍照后的图片会保存在最近添加中
    if (version >= 800 && version <= 802) {
        return YES;

    }
    return NO;
}

// 汉字转拼音
+ (NSString *)transform:(NSString *)chinese
{
    NSMutableString *pinyin = [chinese mutableCopy];
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
    WLog(@"%@", pinyin);
    return [pinyin uppercaseString];
}


+ (UIImage *)urlTransformImgUrl:(NSString *)imageName{
    NSString *path = [NSMutableString stringWithFormat:@"%@",@"res_SXUGImagePager/"];
    NSString *appendPath = [path stringByAppendingString:imageName];
    
    NSString *imagePath = [[NSBundle mainBundle]pathForResource:appendPath ofType:nil];
    UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
    
    if (!image) {
        image = [UIImage imageNamed:imageName];
    }
    return image;
}


//从 html 里面取出 图片 url
+ (NSArray *)filterImage:(NSString *)html
{
    NSMutableArray *resultArray = [NSMutableArray array];
    
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<(img|IMG)(.*?)(/>|></img>|>)" options:NSRegularExpressionAllowCommentsAndWhitespace error:nil];
    NSArray *result = [regex matchesInString:html options:NSMatchingReportCompletion range:NSMakeRange(0, html.length)];
    
    for (NSTextCheckingResult *item in result) {
        NSString *imgHtml = [html substringWithRange:[item rangeAtIndex:0]];
        
        NSArray *tmpArray = nil;
        if ([imgHtml rangeOfString:@"src=\""].location != NSNotFound) {
            tmpArray = [imgHtml componentsSeparatedByString:@"src=\""];
        } else if ([imgHtml rangeOfString:@"src="].location != NSNotFound) {
            tmpArray = [imgHtml componentsSeparatedByString:@"src="];
        }
        
        if (tmpArray.count >= 2) {
            NSString *src = tmpArray[1];
            
            NSUInteger loc = [src rangeOfString:@"\""].location;
            if (loc != NSNotFound) {
                src = [src substringToIndex:loc];
                [resultArray addObject:src];
            }
        }
    }
    
    return resultArray;
}

+ (void)saveJsonData:(NSDictionary *)JsonDic WithFile:(NSString *)FilePath {
    NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documents = [array lastObject];
    NSString *documnetPath = [documents stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",FilePath]];

    //将字典存入指定的本地文件
    [JsonDic writeToFile:documnetPath atomically:YES];
}

+ (NSDictionary *)readJsonDataFromFile:(NSString *)FilePath {

    NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documents = [array lastObject];
    NSString *documnetPath = [documents stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",FilePath]];

    NSDictionary *resultDic = [NSDictionary dictionaryWithContentsOfFile:documnetPath];
    return resultDic;
}

+ (void)removeJsonDataWithFile:(NSString *)FilePath {
    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documents = [array lastObject];
    NSString *documnetPath = [documents stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",FilePath]];

    [fileManager removeItemAtPath:documnetPath error:nil];
}


// 保存自定义数据
+ (void)saveModelData:(NSArray *)modelData WithFile:(NSString *)FilePath{

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",FilePath]];
    NSFileManager *fileM = [NSFileManager defaultManager];
    //    判断文件是否存在，不存在则直接创建，存在则直接取出文件中的内容
    if (![fileM fileExistsAtPath:filePath]) {
        [fileM createFileAtPath:filePath contents:nil attributes:nil];
    }

    [NSKeyedArchiver archiveRootObject:modelData toFile:filePath];
}

+ (NSArray *)readModelDataFromFile:(NSString *)FilePath{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",FilePath]];

    NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    return array;
}

+ (void)removeModelDataWithFile:(NSString *)FilePath{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",FilePath]];
    NSFileManager *fileM = [NSFileManager defaultManager];
    //    判断文件是否存在，不存在则直接创建，存在则直接取出文件中的内容
    [fileM removeItemAtPath:filePath error:nil];
}

+ (void)saveDataWithUserDefaultsSetObject:(id)object ForKey:(NSString *)key {
    [[NSUserDefaults standardUserDefaults] setObject:object forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (id)getDataWithUserDefaultsForKey:(NSString *)key {
    return [[NSUserDefaults standardUserDefaults] objectForKey:key];
}

+ (void)removeDataWithUserDefaultsForKey:(NSString *)key {
    return [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
}

+(NSString *)getUUID
{
    NSString * strUUID = (NSString *)[KeyChainStore load:@"com.company.app.usernamepassword"];

    //首次执行该方法时，uuid为空
    if ([strUUID isEqualToString:@""] || !strUUID)
    {
        //生成一个uuid的方法
        CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);

        strUUID = (NSString *)CFBridgingRelease(CFUUIDCreateString (kCFAllocatorDefault,uuidRef));

        //将该uuid保存到keychain
        [KeyChainStore save:KEY_USERNAME_PASSWORD data:strUUID];

    }
    return strUUID;
}

// 弹出系统警告框
+ (UIAlertView *)showAlert:(NSString *)title message:(NSString *)msg {

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                    message:msg
                                                   delegate:nil
                                          cancelButtonTitle:nil
                                          otherButtonTitles:@"确定",nil];
    alert.delegate = self;
    [alert show];
    return alert;
}

+ (NSString *)filterHTML:(NSString *)html
{
    NSScanner * scanner = [NSScanner scannerWithString:html];
    NSString * text = nil;
    while([scanner isAtEnd]==NO)
    {
        //找到标签的起始位置
        [scanner scanUpToString:@"<" intoString:nil];
        //找到标签的结束位置
        [scanner scanUpToString:@">" intoString:&text];
        //替换字符
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
    }
    NSString * regEx = @"&nbsp;";
    html = [html stringByReplacingOccurrencesOfString:regEx withString:@""];
    
    //    NSString * regEx = @"<([^>]*)>";
    //    html = [html stringByReplacingOccurrencesOfString:regEx withString:@""];
    return html;
}

// 时间格式
+ (NSString *)timeFormat:(NSString *)strDate {
    NSString *divFormat = [strDate substringToIndex:10];
    return divFormat;
}

+ (NSString *)webUrlAppendingString:(NSString *)url dic:(NSDictionary *)parametersDict {

    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];
    secret = [CommonFunc encryptWithText:secret];

    secret = [secret stringByReplacingOccurrencesOfString:@"/" withString:@"%2F"];
    secret = [secret stringByReplacingOccurrencesOfString:@"=" withString:@"%3D"];
    secret = [secret stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];
    NSString *strUrl = [NSString stringWithFormat:@"%@%@",url,secret];
    return strUrl;
}

+(void)ShowWaitView:(BOOL)IsShow
{
    if (IsShow) {
        [[[UIApplication sharedApplication] delegate].window showWait:YES];
    }else{
        [[[UIApplication sharedApplication] delegate].window showWait:NO];
    }
}

//设置状态栏颜色
+ (void)setStatusBarBackgroundColor:(UIColor *)color {

    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
        statusBar.backgroundColor = color;
    }
}

+ (GifView *)animatedGifWithData:(UIImageView *)imgView {
    NSData *localData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Preloader_2" ofType:@"gif"]];

    GifView *dataView = [[GifView alloc] initWithFrame:CGRectMake((imgView.mj_w - 20) * 0.5, (imgView.mj_h - 20) * 0.5, 20, 20) data:localData];
    
    return dataView;
}

+ (GifView *)animatedGifWithDataSize:(CGSize)size {
    NSData *localData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Preloader_2" ofType:@"gif"]];

    GifView *dataView = [[GifView alloc] initWithFrame:CGRectMake((size.width - 40) * 0.5, (size.height - 20) * 0.5, 20, 20) data:localData];

    return dataView;
}

//#pragma mark - 一键检测网络请求
+ (void)                  YJJCDataRequest:(NSString *)url
       success:(void (^)(NSString *successUrl))successUrl
       failure:(void (^)(NSString *failureUrl))failureUrl {
    NSDictionary *parametersDict = @{@"mode":@"native",@"service":@"init",@"content":@{@"screen":@"server"}};
    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];
    NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:secret]};

    // 1、创建请求管理者
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.requestSerializer.timeoutInterval = 3;
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    // 2、发送请求
    [mgr POST:url parameters:paramsDic progress:^(NSProgress * _Nonnull uploadProgress) {
        //        QFLog(@"%@", uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        availableUrl = url;
        WLog(@"%@================",availableUrl);
        [WShareUtil sharedData].cirReqNum = 0;
        [WShareUtil sharedData].reqNum = 0;

        if (successUrl) {
            successUrl(url);
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ServiceExamineRefresh" object:nil];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        WLog(@"失败");

        if ([WShareUtil sharedData].cirReqNum == 0) {
            if ([WShareUtil sharedData].reqNum == 0) {

                [self YJJCDataRequest:@"http://www.sx9511.com/zstapp?" success:^(NSString *successUrl) {

                    [[NSNotificationCenter defaultCenter] postNotificationName:@"ServiceExamineRefresh" object:nil];
                } failure:^(NSString *failureUrl) {

                }];
                [WShareUtil sharedData].reqNum = 1;
            } else if ([WShareUtil sharedData].reqNum == 1){
                [self YJJCDataRequest:@"http://60.205.57.195:21080/zstapp?" success:^(NSString *successUrl) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"ServiceExamineRefresh" object:nil];
                } failure:^(NSString *failureUrl) {

                }];
                [WShareUtil sharedData].reqNum = 2;
            }else if ([WShareUtil sharedData].reqNum == 2){
                [self YJJCDataRequest:@"http://60.205.57.195/zstapp？" success:^(NSString *successUrl) {
                    //                    [[NSNotificationCenter defaultCenter] postNotificationName:@"ServiceExamineRefresh" object:nil];
                } failure:^(NSString *failureUrl) {

                }];
                [WShareUtil sharedData].reqNum = 3;
            }else if ([WShareUtil sharedData].reqNum == 3){
                [self YJJCDataRequest:@"http://www.sx95113.com:21080/zstapp?" success:^(NSString *successUrl) {
                    //                    [[NSNotificationCenter defaultCenter] postNotificationName:@"ServiceExamineRefresh" object:nil];
                } failure:^(NSString *failureUrl) {

                }];
                [WShareUtil sharedData].reqNum = 4;
                [WShareUtil sharedData].cirReqNum = 1;
            }
        }else if ([WShareUtil sharedData].cirReqNum == 1) {

            if ([WShareUtil sharedData].reqNum == 0) {
                [self YJJCDataRequest:@"https://www.sx95113.com/zstapp?" success:^(NSString *successUrl) {
//                    [[NSNotificationCenter defaultCenter] postNotificationName:@"ServiceExamineRefresh" object:nil];
                } failure:^(NSString *failureUrl) {

                }];
                [WShareUtil sharedData].reqNum = 1;
            } else if ([WShareUtil sharedData].reqNum == 1) {
                [self YJJCDataRequest:@"http://www.sx95113.com/zstapp?" success:^(NSString *successUrl) {
//                    [[NSNotificationCenter defaultCenter] postNotificationName:@"ServiceExamineRefresh" object:nil];
                } failure:^(NSString *failureUrl) {

                }];
                [WShareUtil sharedData].reqNum = 2;
            } else if ([WShareUtil sharedData].reqNum == 2){

                [self YJJCDataRequest:@"http://60.205.57.195:21080/zstapp?" success:^(NSString *successUrl) {
//                    [[NSNotificationCenter defaultCenter] postNotificationName:@"ServiceExamineRefresh" object:nil];
                } failure:^(NSString *failureUrl) {

                }];
                [WShareUtil sharedData].cirReqNum = 3;
            }
        }else if ([WShareUtil sharedData].reqNum == 3){
            [self YJJCDataRequest:@"http://60.205.57.195/zstapp?" success:^(NSString *successUrl) {
                //                    [[NSNotificationCenter defaultCenter] postNotificationName:@"ServiceExamineRefresh" object:nil];
            } failure:^(NSString *failureUrl) {

            }];
            [WShareUtil sharedData].reqNum = 4;
        }else if ([WShareUtil sharedData].reqNum == 4){
            [self YJJCDataRequest:@"http://www.sx95113.com:21080/zstapp?" success:^(NSString *successUrl) {
                //                    [[NSNotificationCenter defaultCenter] postNotificationName:@"ServiceExamineRefresh" object:nil];
            } failure:^(NSString *failureUrl) {

            }];
            [WShareUtil sharedData].reqNum = 5;
        }else {
            [WShareUtil showAlert:@"温馨提示" message:@"服务器可能在维修中，请稍后访问"];
            availableUrl = PCReleaseURL;
            [WShareUtil sharedData].cirReqNum = 0;
            [WShareUtil sharedData].reqNum = 0;
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"ServiceExamineRefresh" object:nil];
        }
        if (failureUrl) {
            failureUrl(url);
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"ServiceExamineRefresh" object:nil];
        }
    }];

}

@end
